import { defineStore } from "pinia";
import index from "../views/Layout/index.vue";
//写法一
const useUserStore = defineStore("tagsView", {
  // options
  state: () => ({
    tags: [],
    cacheTags: [],
  }),
  //方法：同步异步
  actions: {
    setCacheTags() {
      this.cacheTags = this.tags
        .filter((item) => item.isKeepAlive)
        .map((item) => item.path);
    },
    //初始化数据
    //缓存 tags中添加数据时 将带有isKeepAlive为true的数据缓存
    initTags(tags) {
      this.tags = tags;
      this.setCacheTags();
    },
    //增
    addTag(item) {
      const { path } = item;
      const flag = this.tags.map((item) => item.path).includes(path);
      if (flag) return;
      this.tags.push(item);
      this.setCacheTags();
    },
    //删改查
    remove(index) {
      //删除state中某个成员
      this.tags.splice(index, 1);
      this.setCacheTags();
    },
    //删除其他
    removeOther(index) {
      if (isNaN(index)) return;
      //删除数组：方案1；正想删除记得退回操作
      //方案2：到着删除
      //注意：this.tags.length不能储存到外面，因为每次循环之后数组长度发上变化
      for (let i = 0; i < this.tags.length; i++) {
        const item = this.tags[i];
        if (item.isAffix || index === i) {
          continue;
        }
        this.tags.splice(i, 1);
        i--;
      }
      this.setCacheTags();
    },
    //删除所有
    removeAll() {
      //删除数组：方案1；正想删除记得退回操作
      //方案2：到着删除
      for (let i = this.tags.length - 1; i >= 0; i--) {
        const item = this.tags[i];
        if (item.isAffix) {
          return;
        }
        this.tags.splice(i, 1);
      }
      this.setCacheTags();
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: "tagsView",
        storage: localStorage,
      },
    ],
  },
});
//写法二
export default useUserStore;
